package com.ipcoder;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.util.Scanner;

public class DatagramSocketName {
    public static void main(String[] args) throws IOException {
        while (true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("向主机:" + InetAddress.getByName
                    ("192.168.18.24").getHostName() + "IP:"
                    + InetAddress.getByName("192.168.18.24").getHostAddress() + "发送消息:");
            //创建UDP套接字
            DatagramSocket ds = new DatagramSocket();
            //创建字节数组接收用户输入的字符串
            byte[] bys = new byte[4096];
            bys = sc.nextLine().getBytes();
            //创建发送包
            DatagramPacket dp = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.18.24"), 9998);
            ds.send(dp);
            ds.close();
            //获取接收客户端的数据
            Socket sk = new Socket("192.168.18.24", 9998);
            InputStream is = sk.getInputStream();
            byte[] bys1 = new byte[1024];
            int len = is.read(bys1);
            String data = new String(bys1, 0, len);
            System.out.println("服务器端说:"+data);
            sk.close();
            is.close();
        }

        //UdpSend();
    }

    public static void UdpSend() throws IOException {
        //创建发送端的套接字
        DatagramSocket data = new DatagramSocket();
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("向主机名称为:" + InetAddress.getByName
                    ("192.168.18.24").getHostName() + " 主机地址为"
                    + InetAddress.getByName("192.168.18.24").getHostAddress() + "发送如下消息:");

            String send = sc.nextLine();
            //创建发送的字符数组
            byte[] bys = send.getBytes();
            //创建发送包
            DatagramPacket yes = new DatagramPacket(bys, bys.length, InetAddress.getByName("192.168.18.24"), 18888);
            data.send(yes);
            //data.close();
        }
    }
}
